/**
 * Created by Wenwu on 7/19/2016.
 * 工具类
 */

define(function () {

	var Config = require('config'), _ = require('ajax');

	var Utilities = {
		getParameterByName: function (name) {
			name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
			var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
				results = regex.exec(location.search);
			return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
		},
		findElement: function (arr, propName, propValue) {
			for (var i = 0; i < arr.length; i++)
				if (arr[i][propName] == propValue)
					return arr[i];
		},
		findWithAttr: function (array, attr, value) {
			for (var i = 0; i < array.length; i += 1) {
				if (array[i][attr] === value) {
					return i;
				}
			}
		},
		jsonObjToBase64: function (json) {
			return btoa(encodeURIComponent(JSON.stringify(json)));
		},
		base64TojsonObj: function (base64) {
			return JSON.parse(decodeURIComponent(atob(base64)));
		},
		pageJump: function (url) {
			location.href = url;
		},
		createCookies: function (name, value, days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				var expires = "; expires=" + date.toGMTString();
			}
			else var expires = "";
			document.cookie = name + "=" + value + expires + "; path=/";
		},
		readCookies: function (name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for (var i = 0; i < ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ') c = c.substring(1, c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
			}
			return null;
		},
		refreshUserInfo: function (callback) {
			_(Config.SERVICE.USERCENTER.MEMBER_DETAIL, {
				id: sessionStorage.id
			}, function (data) {
				// 个人信息存到session
				sessionStorage.userInfo = btoa(encodeURIComponent(JSON.stringify(data.obj)));
				// 未读小红点
				var userInfo = data.obj;
				var el = document.querySelector('.footer > a:last-child');
                if (el!=null&&(userInfo.member.msg != 0  || userInfo.member.greeted != 0 ||userInfo.member.inbox != 0)) {
					var node = document.createElement("span");
					var textnode = document.createTextNode(parseInt(userInfo.member.msg)+parseInt(userInfo.member.greeted)+parseInt(userInfo.member.inbox));
					node.appendChild(textnode);
					el.appendChild(node);
				}
                // 回调
				if (typeof callback === 'function') {
					callback(data.obj);
				}
			});
		},
		// 是否认证
		// isAuth: function(){
		// 	var authFlag = true;
		// 	_(Config.SERVICE.USERCENTER.MEMBER_DETAIL, {
		// 		id: sessionStorage.id
		// 	}, function (data) {
		// 		if(data.obj.member.sfrz==0||data.obj.member.sfjy==1){
		// 			authFlag = false;
		// 			console.log(authFlag);
		// 		}
		// 	});

		// },
		eraseCookie: function (name) {
			createCookie(name, "", -1);
		},
		// restore check list
		restoreCheckList: function (fullListArr, checkedArr) {
			for (var i = 0; i < fullListArr.length; i++) {
				for (var j = 0; j < checkedArr.length; j++) {
					if (fullListArr[i].id == checkedArr[j]) {
						fullListArr[i].checked = true;
					}
				}
			}
		},
		// get checked id string
		getCheckedStr: function (arr) {
			var str = '';
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].checked)
					str += (arr[i].id + ',');
			}
			return str.substr(0, str.length - 1);
		},
		// SESSION相关操作
		sessionUtilities: function () {
			return {
				setUserInfo: function (userInfo) {
					if (typeof(userInfo) === 'object')
						localStorage.setItem('userInfo', JSON.stringify(userInfo));
				},
				getUserInfo: function () {
					// var userInfoStr = localStorage.getItem('userInfo');
					// return userInfoStr === null ? null : JSON.parse(userInfoStr);
					var allInfo = this.getAllInfo();
					return allInfo === null ? null : allInfo.userInfo;
				},
				clearUserInfo: function () {
					localStorage.removeItem('userInfo');
				},
				setAllInfo: function (allInfo) {
					if (typeof(allInfo) === 'object')
						localStorage.setItem('allInfo', JSON.stringify(allInfo));
				},
				getAllInfo: function () {
					var allInfoStr = localStorage.getItem('allInfo');
					return allInfoStr === null ? null : JSON.parse(allInfoStr);
				}
			}
		},
		// loadJssdkSign: function (url, _, href, rawId, callback) {
		// 	_(url, {
		// 		rawId: rawId,
		// 		url: href
		// 	}, function (data) {
		// 		callback(data.data.result);
		// 	});
		// },
		loadWxConfig: function (wx, url, _, href, rawId, jsApiList, callback) {
			var _this = this;
			_(url, {
				rawId: rawId,
				url: href
			}, function (data) {
				var result = data.data.result;
				wx.config({
					debug: false,
					appId: _this.sessionUtilities().getAllInfo().clientInfo.appId,
					timestamp: result.timestamp,
					nonceStr: result.nonceStr,
					signature: result.signature,
					jsApiList: jsApiList
					// jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'hideMenuItems']
				});
				(function (_callback) {
					wx.ready(function () {
						_callback();
					})
				})(callback);
			});
		}

	};
	return Utilities;
});